import java.util.Arrays;

/**
 * @author ZCR
 * @create 2025/9/2 22:56
 */
public class Solution34 {
    public int[] searchRange(int[] nums, int target) {
        int left = lower(nums, target);
        int right = upper(nums, target);
        return new int[]{left, right};
    }

    public int upper(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return -1;
        }
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                // mid = left - 1
                left = mid + 1;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            }
        }
        //left = right + 1
        return left - 1 < 0 || nums[left - 1] != target ? -1 : left - 1;
    }

    public int lower(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return -1;
        }
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                // mid = right + 1=left
                right = mid - 1;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            }
        }
        //left = right + 1
        return left == nums.length || nums[left] != target ? -1 : left;
    }

    public static void main(String[] args) {
        Solution34 solution34 = new Solution34();
        System.out.println(Arrays.toString(solution34.searchRange(new int[]{5, 7, 7, 8, 8, 10}, 8)));
        System.out.println(Arrays.toString(solution34.searchRange(new int[]{5, 7, 7, 8, 8, 10}, 6)));
        System.out.println(Arrays.toString(solution34.searchRange(new int[]{}, 0)));
        System.out.println(Arrays.toString(solution34.searchRange(new int[]{1}, 0)));
        System.out.println(Arrays.toString(solution34.searchRange(new int[]{1,2,3,5,7,9}, 6)));
    }
}
